package com.a2.appa3.ui.activity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Base64;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.a2.appa3.R;
import com.a2.appa3.global.HttpAdress;
import com.a2.appa3.global.Info;
import com.a2.appa3.model.CustomObserver;
import com.a2.appa3.model.network.HttpJsonUtils;
import com.a2.appa3.model.network.entity.req.TabEntityBean;
import com.a2.appa3.model.network.entity.req.WebSocketMsgBean;
import com.a2.appa3.model.network.entity.req.websocktdizhiBena;
import com.a2.appa3.ui.fragment.FragmentBasePagerAdapter;
import com.a2.appa3.ui.fragment.adFragment;
import com.a2.appa3.ui.fragment.chatFragment;
import com.a2.appa3.ui.fragment.contentFragment;
import com.a2.appa3.ui.fragment.userFragment;
import com.a2.appa3.util.BaseLoadingDialog;
import com.a2.appa3.util.EventBus.Eventnumber;
import com.a2.appa3.util.EventBus.Sendfriendlist;
import com.a2.appa3.util.EventBus.changechatlist;
import com.a2.appa3.util.SYSOUtils;
import com.a2.appa3.util.WebSocketUtils2;
import com.a2.appa3.widget.NoScrollViewPager;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.shihao.library.XStatusBarHelper;

public class MainActivity extends BaseActivitySimple {

    NoScrollViewPager mViewPager;
    CommonTabLayout mTabLayout;
    private String websocketUrl;
    private String port;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private Gson mgosn = new Gson();
    private boolean isconnected = true;//第一次进入开启聊天室  22
    private boolean voice = true;//第一次进入消息提示
    //    private List<WebSocketMsgBean> mdatas = new ArrayList<>();
    private BaseLoadingDialog dialog;
    private Vibrator mVibrator;//震动
    private Ringtone mRingtone;//声音

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        XStatusBarHelper.tintStatusBar(this, getResources().getColor(R.color.settingbg));
        FragmentBasePagerAdapter adapter = new FragmentBasePagerAdapter(getSupportFragmentManager(),
                adFragment.newInstance(), chatFragment.newInstance(),
                contentFragment.newInstance(), userFragment.newInstance());

        mViewPager = findViewById(R.id.mViewPager);
        mTabLayout = findViewById(R.id.mTabLayout);
        mViewPager.setAdapter(adapter);
        String[] mTitles = {"应用中心", "聊天", "通讯录", "我的"};
        int[] mIconUnSelectIds = {
                R.mipmap.appad_off, R.mipmap.chat_off,
                R.mipmap.content_off, R.mipmap.user_off};
        int[] mIconSelectIds = {
                R.mipmap.appad_on, R.mipmap.chat_on,
                R.mipmap.content_on, R.mipmap.user_on};
        ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntityBean(mTitles[i], mIconSelectIds[i], mIconUnSelectIds[i]));
        }
        mTabLayout.setTabData(mTabEntities);
        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mViewPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        mViewPager.setOffscreenPageLimit(1);
        mTabLayout.setMsgMargin(3, -3, 5);
        mViewPager.setCurrentItem(1);
        mTabLayout.setCurrentTab(1);
        if (!TextUtils.isEmpty(Info.Token)) {
            get_websocket_adress();
        } else {
            finish();
            Toast.makeText(this, "登录失效，请重新登录", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
        }
        //初始化震动
        mVibrator = (Vibrator) this.getSystemService(Service.VIBRATOR_SERVICE);
        //初始化声音
        Uri notifyUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mRingtone = RingtoneManager.getRingtone(this, notifyUri);
    }

    /**
     * 链接socket
     */
    private void get_websocket_adress() {
        //获取websocket地址和端口
        HttpJsonUtils.getHttpApiInstance()
                .get_websocket_adress(HttpAdress.getuseAdress() + "api/chat/url", Info.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<websocktdizhiBena>() {
                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {

                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {
                        Toast.makeText(MainActivity.this, "请检查网络连接", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    protected void onCustomNext(websocktdizhiBena resCode) {
                        try {
                            dialog = new BaseLoadingDialog(MainActivity.this, R.style.custom_dialog2);
                            dialog.show();
                            //连接websocket，并且处理推送过来的消息
                            websocketUrl = resCode.getChatUrl();
//                            websocketUrl = "http:10.16.56.66:9501";
                            port = resCode.getChatPort();
                            String mUrl = websocketUrl + ":" + port + "/" + Info.user.token;
//                            String mUrl = "ws://10.16.56.66:9501" + "/" + Info.user.token;
                            SYSOUtils.sOut_(mUrl);
                            WebSocketUtils2.getInstance().initWebsocket(mUrl, new WebSocketUtils2.MsgHandle() {
                                @Override
                                public void open() {
                                    isconnected = true;
                                }

                                @Override
                                public void getMsg(String msg) {
                                    dialog.dismiss();
                                    //必须try-catch不然会导致websocket异常关闭
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            SYSOUtils.sOut_("++++++++++++++请求+++++++++++++" + msg);
                                            //判断是不是json
                                            if (isjson(msg)) {
                                                WebSocketMsgBean bean = mgosn.fromJson(msg, WebSocketMsgBean.class);
                                                SYSOUtils.sOut_("接收到的状态是+++++++++++++++++++++++++++++" + bean.status);
                                                if (bean.status == 2 || bean.status == 4 || bean.status == 8 || bean.status == 9) {
                                                    try {
                                                        String string = new String(Base64.decode((((String) bean.msg)).getBytes(), Base64.DEFAULT));
                                                        String text2 = java.net.URLDecoder.decode(string, "utf-8");
                                                        if (text2.contains("img=")) {
                                                            if (bean.status == 2) {
                                                                bean.status = 22;
                                                            }
                                                            if (bean.status == 4) {
                                                                bean.status = 44;
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                    if (!bean.level.equals("98")) {
                                                        SYSOUtils.sOut_("聊天内容即将添加我自己的发言" + bean);
                                                        Info.mdatas.add(bean);
//                                                    if (!isconnected) {
                                                        EventBus.getDefault().post(new changechatlist("fresh"));
                                                        //自己发言
//                                                    if (!Info.user.nickname.equals(bean.nickname)) {
//                                                        if (mVibrator != null && Info.voiceflag) {
//                                                            // 震动 1s
//                                                            mVibrator.vibrate(300);
//                                                        }
//                                                        if (mRingtone != null && Info.shockflag) {
//                                                            mRingtone.play();
//                                                        }
//                                                    }
//                                                    }
                                                    } else {
                                                        SYSOUtils.sOut_("聊天内容群聊即将添加" + bean);
                                                        if (bean != null) {
                                                            Info.mdatas.add(bean);
//                                                        if (!bean.fd.equals("计划任务")) {
//                                                            if (mVibrator != null && Info.voiceflag) {
//                                                                // 震动 1s
//                                                                mVibrator.vibrate(300);
//                                                            }
//                                                            if (mRingtone != null && Info.shockflag) {
//                                                                mRingtone.play();
//                                                            }
//                                                        }
//                                                        if (!isconnected) {
                                                            EventBus.getDefault().post(new changechatlist("refresh"));
//                                                        }
                                                        } else {

                                                        }
                                                    }

                                                } else if (bean.status == 6) {
//                                                //公告
//                                                try {
//                                                    note = "" + bean.msg;
//                                                    gonggao.setText(note + "                 " + note + "                 " + note);
//                                                    gonggao.setSelected(true);
//                                                } catch (Exception e) {
//
//                                                }
                                                } else if (bean.status == 1) {
                                                    //别人进入聊天室
                                                    TextView textView = new TextView(MainActivity.this);
                                                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                                            70);
                                                    params.setMargins(20, 150, 20, 0);
                                                    textView.setLayoutParams(params);
                                                    textView.setText("  " + bean.fd + "：进入了聊天室  ");
                                                    textView.setTextColor(Color.parseColor("#ffffff"));
                                                    textView.setGravity(Gravity.CENTER);
                                                    ObjectAnimator valueAnimator = ObjectAnimator.ofFloat(textView, "translationX", 1200);
                                                    valueAnimator.setDuration(3000);
                                                    valueAnimator.start();
                                                    textView.setBackgroundResource(R.drawable.comeinmember);
                                                    valueAnimator.addListener(new Animator.AnimatorListener() {
                                                        @Override
                                                        public void onAnimationStart(Animator animation) {

                                                        }

                                                        @Override
                                                        public void onAnimationEnd(Animator animation) {
//                                                        reletivecontent.removeView(textView);
                                                        }

                                                        @Override
                                                        public void onAnimationCancel(Animator animation) {

                                                        }

                                                        @Override
                                                        public void onAnimationRepeat(Animator animation) {

                                                        }
                                                    });
                                                } else if (bean.status == 5) {
//                                                enterdata.setText(String.valueOf(bean.msg) + "");
//                                                fasong.setClickable(false);
//                                                fasongpic.setClickable(false);
//                                                enterdata.setEnabled(false);
                                                    //已被禁言
                                                    Toast.makeText(MainActivity.this, bean.msg.toString() + "", Toast.LENGTH_SHORT).show();
                                                } else if (bean.status == 13) {
                                                    //禁止发言过快
                                                    Toast.makeText(MainActivity.this, "说话太快了呦，歇会儿吧！！", Toast.LENGTH_SHORT).show();
                                                } else if (bean.status == 7) {
                                                    try {
                                                        SYSOUtils.sOut_("状态7" + bean + "++++++++++++++++++++++++++" + bean.nickname);
                                                        Info.user.nickname = bean.nickname;
                                                        if (Info.user.nickname.contains("***")) {
                                                            startActivity(new Intent(MainActivity.this, changeNikeDiolog.class));
                                                        }
                                                    } catch (Exception e) {
                                                    }
                                                    //                                                Toast.makeText(MainActivity.this, "状态7"+bean.msg, Toast.LENGTH_SHORT).show();
                                                    //限制发言//0能发言 1不能发言
//                                                if (bean.anS.equals("1")) {

//                                                    enterdata.setText("平台暂无发言权限");
//                                                    fasong.setClickable(false);
//                                                    fasongpic.setClickable(false);
//                                                    enterdata.setEnabled(false);
//                                                }
//                                                if (bean.nS.equals("1")) {
//                                                    enterdata.setText("前两天充值不少于" + resCode.getRech() + "元；打码量不少于" + resCode.getBet() + "元");
//                                                    fasong.setClickable(false);
//                                                    fasongpic.setClickable(false);
//                                                    enterdata.setEnabled(false);
//                                                } else {
//                                                    fasong.setClickable(true);
//                                                    fasongpic.setClickable(true);
//                                                    enterdata.setEnabled(true);
//                                                }
                                                } else if (bean.status == 10) {
                                                    //删除消息
                                                    for (int i = 0; i < Info.mdatas.size(); i++) {
                                                        if (Info.mdatas.get(i).msg.equals(bean.msg)) {
                                                            Info.mdatas.remove(i);
//                                                        if (ismovetoposition) {
//                                                            //不动
//                                                        } else {
//                                                            if (Info.mdatas.size() != 0) {
//                                                                MoveToPosition(manager, recyclewviewlist, mdatas.size() - 1);
//                                                            }
//                                                        }
                                                        }
                                                    }
                                                } else if (bean.status == 3) {
                                                    Toast.makeText(MainActivity.this, "账号在它处登录", Toast.LENGTH_LONG).show();
//                                                SpUtils.clearusername(MainActivity.this);
//                                                SpUtils.clearloginpass(MainActivity.this);
                                                    Info.Token = null;
                                                    //断开Socket
                                                    WebSocketUtils2.getInstance().ondestoryWebsocket();
                                                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                                                    finish();
                                                } else if (bean.status == 15) {
                                                    //跟单
//                                                String string1 = new String(Base64.decode(((String) bean.msg).getBytes(), Base64.DEFAULT));
//                                                if (!ispingbi) {
//                                                    mdatas.add(bean);
//                                                }
                                                } else if (bean.status == 22) {
//                                                if (isconnected) {
//                                                    isconnected = false;
//                                                }
//                                                SYSOUtils.sOut_("首页列表22" + bean.msg.toString());
                                                    EventBus.getDefault().post(new Sendfriendlist(bean.msg.toString()));

                                                } else if (bean.status == 19) {
                                                    //可以快速进入的房间列表
//                                                mdatas.add(bean);
                                                } else if (bean.status == 25) {
                                                    Toast.makeText(MainActivity.this, "被移出房间", Toast.LENGTH_SHORT).show();
                                                } else if (bean.status == 24) {
//                                                Toast.makeText(MainActivity.this, "删除信息", Toast.LENGTH_SHORT).show();
                                                } else if (bean.status == 23) {
                                                    Toast.makeText(MainActivity.this, "房间信息有变动", Toast.LENGTH_SHORT).show();
                                                } else if (bean.status == 21) {
//                                                String str ="{\"user_id\":209111, \"name\":\n" +"\"jscs002\", \"img\":\"\", \"id\":2}";
//                                                SYSOUtils.sOut_("收到好友请求" + bean.msg.toString());
                                                    Toast.makeText(MainActivity.this, "收到好友请求", Toast.LENGTH_SHORT).show();
                                                } else if (bean.status == 20) {
                                                    Toast.makeText(MainActivity.this, "用户聊过天的房间和好友", Toast.LENGTH_SHORT).show();
                                                } else if (bean.status == 18) {
                                                    Toast.makeText(MainActivity.this, "加入房间成功", Toast.LENGTH_SHORT).show();
                                                } else if (bean.status == 17) {
                                                    Toast.makeText(MainActivity.this, bean.msg.toString(), Toast.LENGTH_SHORT).show();
                                                }
                                            } else {
                                                SYSOUtils.sOut_("++++++++++++++++++++++++++++++++++++++++++");
                                            }
                                        }
                                    });
                                    if (isconnected) {
                                        try {
                                            String str = "";
                                            final JSONObject result = new JSONObject();
                                            result.put("controller", "Action");
                                            result.put("action", "exitWindow");
                                            String text1 = URLEncoder.encode(result.toString(), "utf-8");
                                            String encodeWord = null;
                                            encodeWord = Base64.encodeToString(text1.getBytes("utf-8"), Base64.DEFAULT);
                                            str = "type=ins&message=" + encodeWord;
                                            WebSocketUtils2.getInstance().sendMsg(str);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        isconnected = false;
                                    }
                                }

                                @Override
                                public void onClosed() {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            dialog.dismiss();
                                        }
                                    });
                                    isconnected = false;
                                }

                                @Override
                                public void onFailure() {
                                    isconnected = false;
                                }

                                @Override
                                public void onBeginconnect() {

                                }
                            });
                        } catch (Exception e) {

                        }
                    }
                });
        if (TextUtils.isEmpty(Info.user.isPhone)) {
            Toast.makeText(MainActivity.this, "请绑定手机号", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(MainActivity.this, changephoneDiolog.class);
            startActivity(intent);
        }
    }


    @Override
    protected int setContentView() {
        return R.layout.activity_main;
    }

    /**
     * 再按一次退出程序
     */
    private long currentBackPressedTime = 0;
    private static int BACK_PRESSED_INTERVAL = 5000;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN
                && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - currentBackPressedTime > BACK_PRESSED_INTERVAL) {
                currentBackPressedTime = System.currentTimeMillis();
                SYSOUtils.sOut_("再按一次，退出应用！");
                return true;
            } else {
                finish(); // 退出
            }
            return false;

        } else if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        销毁EventBus
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(Eventnumber eventnumber) {
        if (eventnumber.number.equals("1")) {
            mViewPager.setCurrentItem(1);
            mTabLayout.setCurrentTab(1);
        }
    }


    private boolean isjson(String string) {
        try {
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(string);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}

